package cn.kgc.zuxin.controller;

import cn.kgc.zuxin.common.R;
import cn.kgc.zuxin.entity.Category;
import cn.kgc.zuxin.mapper.CategoryMapper;
import cn.kgc.zuxin.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {
    @Resource
    CategoryService categoryService;

    @PostMapping
    @ResponseBody
    public R<String> save(@RequestBody Category category){
        System.out.println(category);
        categoryService.save(category);
        System.out.println("222");
        return R.success("添加成功");
    }

    @GetMapping("/page")
    @ResponseBody
    public R<Page> page(int page,int pageSize){
        Page<Category> page1 = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(page1,queryWrapper);
        return R.success(page1);
    }

    @DeleteMapping
    @ResponseBody
    public R<String> delete(Long ids){
//        categoryService.removeById(ids);
         categoryService.remove(ids);
        return R.success("删除成功");
    }
    @PutMapping
    @ResponseBody
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }
    /**
     * 根据条件查询分类数据
     *
     * @param category
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public R<List<Category>> list(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
